<template>
  <div>
    <h1>商品列表</h1>
    <div style="margin-bottom: 10px">
      <el-button type="primary" @click="onAddProdShow">新增商品</el-button>
      <el-button type="danger" @click="onDeleteBatch">批量删除</el-button>
    </div>
    <!-- 表格数据 -->
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="30px" />
      <el-table-column prop="prodId" label="ID" width="40px" />
      <el-table-column prop="prodSpu" label="SPU" width="60px" />
      <el-table-column prop="prodName" label="名称" width="80px" />
      <el-table-column prop="typeName" label="类型" width="90px" />
      <el-table-column prop="brandName" label="品牌" width="80px" />
      <el-table-column prop="unitName" label="单位" width="60px" />
      <el-table-column prop="tagName" label="标签" width="60px" />
      <el-table-column prop="apprName" label="供应商" />
      <el-table-column label="图片" width="60px">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.prodImage"
          />
        </template>
      </el-table-column>
      <el-table-column prop="prodStatus" label="状态" width="70px">
        <template #default="scope">
          <el-tag
            :type="scope.row.prodStatus == 0 ? 'success' : 'danger'"
            size="small"
            >{{ scope.row.prodStatus == 0 ? "上架" : "下架" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="dictLabel" label="种类" width="80px" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" />
    </el-table>
    <!-- 分页 -->
    <div style="margin-top: 20px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加商品---对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="新增商品" width="500">
        <el-form :model="form">
          <el-form-item label="商品类型" :label-width="formLabelWidth">
            <el-radio-group v-model="form.kindId">
              <el-radio value="0">实物商品</el-radio>
              <el-radio value="1">虚拟商品</el-radio>
              <el-radio value="2">卡密/网盘</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品分类" :label-width="formLabelWidth">
            <el-tree-select
              v-model="form.typeId"
              :data="typeListTree"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="商品名称" :label-width="formLabelWidth">
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品SPU" :label-width="formLabelWidth">
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品品牌" :label-width="formLabelWidth">
            <el-select v-model="form.brandId" placeholder="请选择商品品牌">
              <el-option
                v-for="item in brandList"
                :key="item.brandId"
                :label="item.brandName"
                :value="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品单位" :label-width="formLabelWidth">
            <el-select v-model="form.unitId" placeholder="请选择商品单位">
              <el-option
                v-for="item in unitList"
                :key="item.unitId"
                :label="item.unitName"
                :value="item.unitId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签" :label-width="formLabelWidth">
            <el-select v-model="form.tagId" placeholder="请选择商品标签">
              <el-option
                v-for="item in tagList"
                :key="item.tagId"
                :label="item.tagName"
                :value="item.tagId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" :label-width="formLabelWidth">
            <el-select v-model="form.apprId" placeholder="请选择供应商">
              <el-option
                v-for="item in apprList"
                :key="item.apprId"
                :label="item.apprName"
                :value="item.apprId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品缩略图" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/shop/loadImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeAdd">取消</el-button>
            <el-button type="primary" @click="onSubmitProd"> 提交 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { ElMessage, type UploadProps } from "element-plus";
import {
  getProdList,
  addProd,
  getTypeSelectTree,
  getBrandList,
  getUnitList,
  getTagList,
  getApprList,
  deleteBatchProd,
} from "../api/api";

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
});

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
  apprId: null,
  brandId: null,
  kindId: null,
  prodImage: "",
  prodName: "",
  prodSpu: "",
  prodStatus: 0,
  tagId: null,
  typeId: null,
  unitId: null,
});

const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

const onDeleteBatch = () => {
  console.log("onDeleteBatch", multipleSelection.value);
  let num = multipleSelection.value;
  if (num == null || num.length <= 0) {
    ElMessage.warning("请先选择要删除的数据");
    return;
  }
  ElMessageBox.confirm("删除后无法恢复，确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      deleteBatchProd(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消成功",
      });
    });
};

const imageUrl = ref("");
const headers = ref({
  token: sessionStorage.getItem("token"),
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  imageUrl.value = response.data;
};

const onAddProdShow = () => {
  console.log("onAddProdShow");
  dialogFormVisible.value = true;
};

const onSubmitProd = () => {
  form.value.prodImage = imageUrl.value;
  addProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadProdList();
      closeAdd();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const closeAdd = () => {
  console.log("closeAdd");
  form.value = {
    apprId: null,
    brandId: null,
    kindId: null,
    prodImage: "",
    prodName: "",
    prodSpu: "",
    prodStatus: 0,
    tagId: null,
    typeId: null,
    unitId: null,
  };
  imageUrl.value = "";
  dialogFormVisible.value = false;
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadProdList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadProdList();
};

const loadProdList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

const typeListTree = ref([]);
const brandList = ref([]);
const unitList = ref([]);
const tagList = ref([]);
const apprList = ref([]);

onMounted(() => {
  loadProdList();
  getTypeSelectTree().then((res) => {
    if (res.data.code == 200) {
      typeListTree.value = res.data.data;
    }
  });
  getBrandList().then((res) => {
    if (res.data.code == 200) {
      brandList.value = res.data.data;
    }
  });
  getUnitList().then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  getTagList().then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });
  getApprList().then((res) => {
    if (res.data.code == 200) {
      apprList.value = res.data.data;
    }
  });
});
</script>

<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<!-- 图片样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
